<template>
  <div class="templateManagement" id="templateManagement">
    <div class="btns">
      <a-button class="addButton" type="primary" @click="downloadTemplate">
        下载模板
      </a-button>
      <a-button class="addButton1" type="primary" @click="uploadEditorAll">
        上传至可视化编辑器
      </a-button>
    </div>
    <div class="tmp-container" v-if="tokenStr">
      <div class="side-left">
        <span>项目管理文件目录</span>
        <div class="side-left-box">
          <a-select
            style="width: 100%"
            v-model:value="projectName"
            :fieldNames="{
              label: 'dirName',
              value: 'dirId',
            }"
            @change="onSelectPro"
            placeholder="请选择"
            showSearch
            :options="projectOptions"
            :filter-option="filterOption2"
          ></a-select>

          <div
            class="tree-container right-tree"
            
          >
          <!-- :style="handleTypeNum == 2 ? 'height: 40%' : 'height: 85%'" -->
            <a-tree
              style="width: 100%"
              show-icon="false"
              :tree-data="siteTreeList"
              :selectable="handleTypeNum == 2 ? true : false"
              :defaultExpandAll="true"
              :fieldNames="fieldNames2"
              :checkable="handleTypeNum == 2 ? false : true"
              v-model:checkedKeys="checkedKeys"
              v-model:selectedKeys="selectedKeys"
              :checkStrictly="false"
              @select="checked_Keys"
              @check="handleTreeCheck"
            >
              <template #icon="{ data }">
                <i
                  class="iconfont icon-a-Folder-openhui"
                  style="color: rgba(0, 0, 0, 0.2); font-size: 20px"
                  v-if="!data.fileFlag && !data.children.length"
                ></i>
              </template>
              <template #switcherIcon="{ dataRef, defaultIcon }">
                <img
                  src="@/assets/imgs/folderOpen.png"
                  alt=""
                  srcset=""
                  v-if="!dataRef.fileFlag"
                  :class="handleTypeNum == 1 ? 'imgOpen' : 'imgOpen2'"
                />
                <component :is="defaultIcon" v-else />
              </template>
              <template #title="record">
                <div :class="record.fileFlag && 'iconys'">
                  <i
                    class="iconfont icon-a-filewenjian"
                    v-if="record.fileFlag"
                    style="margin-left: -15px"
                  ></i>
                  <span>{{ record.name }}</span>
                </div>
              </template>
            </a-tree>
          </div>
          <div
            class="set-cate"
            v-if="!projectOptions.length && handleTypeNum == 2 && tokenStr"
          >
            <span>当前项目列表为空</span>
            <a-button class="addButton" type="primary" @click="setCate"
              >新建项目</a-button
            >
          </div>
          <div
            class="table-container"
            v-if="handleTypeNum == 2 && configData2.records.length"
          >
            <!-- 表格展示部分 -->
            <baseTable
              :columns="columns.fileColumns"
              :dataSource="configData2.records"
              :row-selection="1"
              :isSelect="true"
              :scroll="scroll"
              ref="searchBaseTables"
              :isShowPagination="isShowPagination"
              :showCheckDelete="showCheckDelete"
              :disabledValue="true"
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.ellipsis">
                  <table-tool-tip
                    :text="text"
                    :column="column"
                  ></table-tool-tip>
                </template>
                <template v-if="column.dataIndex === 'oparation'">
                  <a class="eidtRecords" @click="removeItem(record)">移除</a>
                </template>
              </template>
            </baseTable>
          </div>
          <a-button
            class="upload-btn"
            type="primary"
            @click="uploadFile"
            v-if="handleTypeNum == 2"
            v-preReClick
            >上传</a-button
          >
        </div>
      </div>
      <!-- ---------------------分界线---------------------- -->
      <span
        class="iconfont arrows icon-a-doubleright"
        v-if="handleTypeNum == 1"
      ></span>
      <span class="iconfont arrows icon-a-doubleleft" v-else></span>
      <div class="side-left">
        <span class="title-right"
          >站点模板管理文件目录
          <a-tooltip placement="right">
            <template #title>
              <span>来源非低代码编辑器平台的文件不支持上传</span>
            </template>
            <span
              style="color: rgba(0, 0, 0, 0.45); margin-left: 5px"
              class="iconfont icon-hint1"
            ></span>
          </a-tooltip>
        </span>
        <div class="side-left-box">
          <a-select
            style="width: 100%"
            v-model:value="siteId"
            :fieldNames="{
              label: 'siteName',
              value: 'id',
            }"
            placeholder="请选择"
            showSearch
            @change="siteChange"
            :options="siteOptions"
            :filter-option="filterOption"
          ></a-select>

          <div
            class="tree-container right-tree"
          >
            <a-tree
              style="width: 100%;"
              v-model:expandedKeys="expandedKeys"
              v-model:selectedKeys="selectedKeys"
              v-model:checkedKeys="checkedKeys"
              show-icon="false"
              :tree-data="defaultData"
              :selectable="handleTypeNum == 1 ? true : false"
              :defaultExpandAll="true"
              :checkable="handleTypeNum == 1 ? false : true"
              :fieldNames="fieldNames"
              @select="checked_Keys"
              @check="handleTreeCheck"
            >
              <template #icon="{ data }">
                <i
                  class="iconfont icon-a-Folder-openhui"
                  style="color: rgba(0, 0, 0, 0.2); font-size: 20px"
                  v-if="!data.fileFlag && !data.children || !data.fileFlag && !data.children.length"
                ></i>
              </template>

              <template #switcherIcon="{ dataRef, defaultIcon }">
                <img
                  src="@/assets/imgs/folderOpen.png"
                  alt=""
                  srcset=""
                  v-if="!dataRef.fileFlag"
                  :class="handleTypeNum == 2 ? 'imgOpen' : 'imgOpen2'"
                />
                <component :is="defaultIcon" v-else />
              </template>
              <template #title="record">
                <div :class="record.fileFlag && 'iconys'">
                  <i
                    class="iconfont icon-a-filewenjian"
                    v-if="record.fileFlag"
                    style="margin-left: -15px"
                  ></i>
                  <span>{{ record.name }}</span>
                </div>
              </template>
            </a-tree>
          </div>
          <div
            class="table-container"
            v-if="handleTypeNum == 1 && configData2.records.length"
          >
            <!-- 表格展示部分 -->
            <baseTable
              :columns="columns.fileColumns"
              :dataSource="configData2.records"
              :row-selection="1"
              :isSelect="true"
              :scroll="scroll"
              ref="searchBaseTables"
              :isShowPagination="isShowPagination"
              :showCheckDelete="showCheckDelete"
              :disabledValue="true"
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.ellipsis">
                  <table-tool-tip
                    :text="text"
                    :column="column"
                  ></table-tool-tip>
                </template>
                <template v-if="column.dataIndex === 'oparation'">
                  <a class="eidtRecords" @click="removeItem(record)">移除</a>
                </template>
              </template>
            </baseTable>
          </div>
          <div class="btns">
            <a-button
              type="primary"
              @click="copyFiles"
              v-if="handleTypeNum == 1"
              v-preReClick
              >复制</a-button
            >
          </div>
        </div>
      </div>
    </div>

    <templatemodel
      @getProList="getProList"
      v-if="isVisible"
      :isVisible="isVisible"
      @handleCancle="handleCancle"
      :relativePath="IsUpload"
      :tokenStr="tokenStr"
      :modelType="modelType"
      @handleOk="handleOk"
    ></templatemodel>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  computed,
  watch,
  reactive,
  onMounted,
  onBeforeUnmount,
  nextTick,
  createVNode,
} from "vue";
import baseTable from "@/components/table/baseTable.vue";
import { scrollType } from "@/type.d";
import columns from "@/components/table/tableConfig/tableColumn/configTableColumn";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import getters from "@/store/getters";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { routerPerm } from "@/utils/common";
import templatemodel from "./templateModel.vue";
const btnPerm = ref<any[]>([]);
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "name",
  key: "relativePath",
});
const fieldNames2 = reactive<dataSourceType>({
  title: "name",
  key: "id",
});
//interface
interface DataList {
  [propName: string | number]: any;
}

// data
const projectName = ref<any>(null);
const siteId = ref<any>(null);
const projectOptions = ref<any[]>([]);
const siteOptions = ref<dataSourceType[]>([]); // 站点下拉列表
const defaultData = ref<any[]>([]);
const siteTreeList = ref<any[]>([]);
const userInfo = getters.userInfo();
const checkedKeys = ref<any[]>([]);
const checkedKeys2 = ref<any[]>([]);
const handleTypeNum = ref<any>(1);
const rigthCheckable = ref<any>(true);
//表格数据
let configData = reactive<DataList>({ records: [] });
let configData2 = reactive<DataList>({ records: [] });

const expandedKeys = ref<(string | number)[]>([]);
const selectedKeys = ref<string[]>([]);
const isShowPagination = ref<boolean>(false); // 是否需要配分页器
const showCheckDelete = false; // 是否需要分页器中的自定义
const isVisible = ref<boolean>(false); //移动弹窗
const modelType = ref<number>();
let IsUpload = ref<any>("");
//表格数据
let scroll: scrollType = reactive({ y: "100", isFixed: true });
const tokenStr = ref<any>();

// methods
// 获取低代码项目管理目录
const getProList = async () => {
  const data = {
    lowCodeToken:
      tokenStr.value,
  };
  const res = await request.fetchLowCodeTplDirs(data);
  projectOptions.value = res;
  if (projectOptions.value && projectOptions.value.length) {
    projectName.value = projectOptions.value[0].dirId;
    getTreeList(projectName.value);
  }
};
// 选择项目
const onSelectPro = (val: string, option: any) => {
  IsUpload.value = "";
  selectedKeys.value[0] = "";
  checkedKeys.value = [];
  getTreeList(projectName.value);
};
// 低代码模板目录查询
const getTreeList = async (id: any) => {
  const data = {
    dirId: id,
    lowCodeToken:
      tokenStr.value,
  };
  const res = (await request.fetchLowCodetplTree(data)) || [];
  siteTreeList.value = loop([res]);
};

// 移除
const removeItem = (item: any) => {
    configData2.records = configData2.records.filter(
      (i: any) => i.id !== item.id
    );
    checkedKeys.value = JSON.parse(
      JSON.stringify(configData2.records.map((item: any) => item.id))
    );
};
// 确认下载模板
const copyFiles = () => {
  const tplIdList = configData2.records.map((item: any) => item.id);
  if (tplIdList.length < 1) {
    return message.error("请勾选项目管理文件目录！");
  }
  if (!IsUpload.value) {
    return message.error("请选中站点模板管理文件目录！");
  }
  const data = {
    lowCodeToken: tokenStr.value,
    siteId: siteId.value,
    tplDir: IsUpload.value,
    // tplIds: checkedKeys.value,
    tplIds: tplIdList,
  };
  request
    .downloadTpl(data)
    .then((res: any) => {
      if (res.code === "00000 00000") {
        checkedKeys.value = [];
        getTplSchemes(siteId.value); // 重新获取站点数据
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 确认上传站点模板
const uploadFile = () => {
  const tplIdList = configData2.records.map((item: any) => item.id);
  if (tplIdList.length < 1) {
    return message.error("请勾选站点模板管理文件目录！");
  }
  if (!IsUpload.value) {
    return message.error("请选中项目管理文件目录！");
  }
  const data = {
    lowCodeToken: tokenStr.value,
    siteId: siteId.value,
    tplDir: IsUpload.value,
    tplIds: tplIdList,
  };
  console.log(data);
  request
    .uploadTpl(data)
    .then((res: any) => {
      if (res.code === "00000 00000") {
        checkedKeys.value = [];
        getTreeList(projectName.value); // 重新获取低代码数据
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

// 选中则边栏
const checked_Keys = async (obj: any, info: any) => {
  nextTick(() => {
    selectedKeys.value[0] = obj[0] || selectedKeys.value[0];
    IsUpload.value = selectedKeys.value[0];
    if (!IsUpload.value) {
      sessionStorage.removeItem("relativePaths");
    } else {
      sessionStorage.relativePaths = IsUpload.value;
    }
  });
};
// 选中复选框
const handleTreeCheck = (keys: any) => {

};
// 下载模版
const downloadTemplate = () => {
  selectedKeys.value = [];
  nextTick(() => {
    checkedKeys.value = [];
    checkedKeys2.value = [];
    sessionStorage.handleType = 1;
    handleTypeNum.value = 1;
    fetchSiteList();
    getProList(); //低代码项目下拉列表
    if(!tokenStr.value) {
      isVisible.value = true;
      modelType.value = 6;
    }
  });
};
// 上传编辑器(多个)
const uploadEditorAll = () => {
  selectedKeys.value = [];
  nextTick(() => {
    checkedKeys.value = [];
    checkedKeys2.value = [];
    sessionStorage.handleType = 2;
    handleTypeNum.value = 2;
    fetchSiteList();
    getProList();
    rigthCheckable.value = false;
    if(!tokenStr.value) {
      isVisible.value = true;
      modelType.value = 7;
    }
  });
};
const setCate = () => {
  isVisible.value = true;
  modelType.value = 4;
};
const findName = (id: any, dataList: DataList[] = []): any => {
  for (let i in dataList) {
    if (dataList[i].id === id) {
      return dataList[i].name;
    }
    if (dataList[i].children) {
      let result = findName(id, dataList[i].children);
      if (result !== null) {
        return result;
      }
    }
  }
  return null;
};
const findFileFlag = (id: any, dataList: DataList[] = []): any => {
  for (let i in dataList) {
    if (dataList[i].id === id) {
      return dataList[i].fileFlag;
    }
    if (dataList[i].children) {
      let result = findFileFlag(id, dataList[i].children);
      if (result !== null) {
        return result;
      }
    }
  }
  return null;
};

const findName2 = (id: any, dataList: DataList[] = []): any => {
  for (let i in dataList) {
    if (dataList[i].relativePath === id) {
      return dataList[i].name;
    }
    if (dataList[i].children) {
      let result = findName2(id, dataList[i].children);
      if (result !== null) {
        return result;
      }
    }
  }
  return null;
};
const findFileFlag2 = (id: any, dataList: DataList[] = []): any => {
  for (let i in dataList) {
    if (dataList[i].relativePath === id) {
      return dataList[i].fileFlag;
    }
    if (dataList[i].children) {
      let result = findFileFlag2(id, dataList[i].children);
      if (result !== null) {
        return result;
      }
    }
  }
  return null;
};

watch(checkedKeys, (newVal: any, oldVal: any) => {
  configData2.records = [];
  for (let i = 0; i < checkedKeys.value.length; i++) {
    if (handleTypeNum.value == 1) {
      let tplName = findName(checkedKeys.value[i], siteTreeList.value);
      let tplFileFlag = findFileFlag(checkedKeys.value[i], siteTreeList.value);
      const obj = {
        id: checkedKeys.value[i],
        name: tplName,
        fileFlag: tplFileFlag,
      };
      if (obj.fileFlag) {
        configData2.records.push(obj);
      }
    } else {
      let tplName2 = findName2(checkedKeys.value[i], defaultData.value);
      let tplFileFlag2 = findFileFlag2(checkedKeys.value[i], defaultData.value);
      const obj2 = {
        id: checkedKeys.value[i],
        name: tplName2,
        fileFlag: tplFileFlag2,
      };
      if (obj2.fileFlag) {
        configData2.records.push(obj2);
        console.log(configData2.records, "configData2.records");
      }
    }
  }
});

// 关闭弹窗
const handleCancle = () => {
  isVisible.value = false;
};
const handleOk = () => {
  isVisible.value = false;
};

//获取站点列表
const fetchSiteList = async () => {
  const data: {} = {
    // orgId: userInfo.orgId,
    userId: userInfo.userId,
    allPermissions: true,
  };
  siteOptions.value = await request.fetchStationGroupList(data);
  if (siteOptions.value && siteOptions.value.length) {
    siteId.value = siteOptions.value[0].id;
    getTplSchemes(siteId.value);
  }
};
const filterOption = (input: string, option: any) => {
  return option.siteName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const filterOption2 = (input: string, option: any) => {
  return option.dirName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
// 切换站点
const siteChange = () => {
  IsUpload.value = "";
  selectedKeys.value[0] = "";
  checkedKeys.value = [];
  getTplSchemes(siteId.value);
};
const getTplSchemes = async (id: any) => {
  const res = await request.fetchTplSchemes({ siteId: id });
  if (res) {
    defaultData.value = loop2(res);
  }
};
const loop = (datalist: DataList[] = []): DataList[] => {
  for (let i in datalist) {
    if (datalist[i].fileFlag) {
      if (sessionStorage.handleType == 1) {
        datalist[i].disabled = false;
      } else if (sessionStorage.handleType == 2) {
        datalist[i].disabled = true;
      } else {
        datalist[i].disabled = false;
      }
    } else {
      if (sessionStorage.handleType == 1) {
        if (!datalist[i].children.length) {
          datalist[i].disabled = true;
        } else {
          datalist[i].disabled = false;
        }
      } else if (sessionStorage.handleType == 2) {
        datalist[i].disabled = false;
      } else {
        datalist[i].disabled = false;
      }
    }
    if (datalist[i].children) {
      loop(datalist[i].children);
    }
  }
  return datalist;
};
const loop2 = (datalist: DataList[] = []): DataList[] => {
  for (let i in datalist) {
    if (datalist[i].fileFlag) {
      if (sessionStorage.handleType == 1) {
        datalist[i].disabled = true;
      } else if (sessionStorage.handleType == 2) {
        if (datalist[i].tplSource == 1) {
          datalist[i].disabled = true;
        } else {
          datalist[i].disabled = false;
        }
      } else {
        datalist[i].disabled = true;
      }
    }else {
      if (sessionStorage.handleType == 2) {
        if (!datalist[i].children || !datalist[i].children.length) {
          datalist[i].disabled = true;
        } else {
          datalist[i].disabled = false;
        }
      } else if (sessionStorage.handleType == 1) {
        datalist[i].disabled = false;
      } else {
        datalist[i].disabled = false;
      }
    }
    if (datalist[i].children) {
      loop2(datalist[i].children);
    }
  }
  return datalist;
};
// 低代码跳转回来之后
const getToken = () => {
  tokenStr.value = sessionStorage.ken;
  if (tokenStr.value) {
    handleTypeNum.value = sessionStorage.handleType || 1;
    getProList(); //低代码项目下拉列表
  }
};

//onmounted
onMounted(() => {
  fetchSiteList(); //获取站点列表
  getToken();
  btnPerm.value = routerPerm();
});

onBeforeUnmount(() => {
  sessionStorage.removeItem("ken");
});
</script>

<style lang="less" scoped>
.templateManagement {
  width: 100%;
  height: calc(100% - 72px);
  background-color: #fff;
  padding: 16px;
  .btns {
    display: flex;
    padding-bottom: 16px;
    .addButton1 {
      margin-left: 16px;
    }
  }
  .tmp-container {
    height: calc(100% - 72px);
    display: flex;
    justify-content: space-between;
    .arrows {
      margin: auto;
      font-size: 50px;
      color: #aaaaaa;
    }
    .side-left {
      width: 45%;
      .side-left-box {
        display: flex;
        flex-direction: column;
        padding: 16px;
        width: 100%;
        height: 100%;
        border: 1px solid #d7d7d7;
        .tree-container {
          margin-top: 16px;
          width: 100%;
          height: 85%;
          overflow-y: scroll;
          // border-bottom: 1px solid #d7d7d7;
        }
        .btns {
          position: absolute;
          bottom: 30px;
          right: 50px;
          width: 150px;
          display: flex;
          justify-content: end;
        }
        .upload-btn {
          position: absolute;
          bottom: 50px;
          left: 46%;
        }
        .set-cate {
          span {
            font-size: 16px;
            margin-bottom: 20px;
          }
          position: absolute;
          top: 38%;
          left: 29%;
          display: flex;
          flex-direction: column;
          align-items: center;
          z-index: 2;
        }
      }
      .title-right {
        display: flex;
        align-items: center;
      }
    }
  }
  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    padding-right: 16px;
  }
  .eidtRecords:last-child {
    margin-right: 0;
  }

  ::v-deep(.titleBox) {
    display: flex;
    align-items: center;
    justify-items: center;
    .titleTip {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-left: 16px;
    }
  }

  ::v-deep(.ant-table-cell) {
    vertical-align: middle;
  }
}
.iconys {
  transform: translateX(-10px);

  i {
    color: rgb(153, 153, 153);
  }

  span {
    margin-left: 4px;
  }
}
.img-em {
  // margin-left: -24px;
}
</style>
<style lang="less" scoped>
.side-left {
  .ant-input-search {
    margin-top: 16px;
  }

  :deep(.ant-tree) {
    height: calc(100% - 35px);
    overflow: auto;

    .ant-tree-treenode {
      width: 100%;

      .ant-tree-node-content-wrapper {
        width: 100%;
      }
    }

    .ant-tree::-webkit-scrollbar {
      display: none;
    }

    .ant-tree:hover::-webkit-scrollbar {
      display: block;
    }

    .ant-tree-list-scrollbar-thumb {
      height: auto !important;
    }

    .ant-tree-list-holder {
      overflow-y: unset !important;
    }
  }
}
.fileFlags {
  display: flex;
  align-items: center;

  .iconfont {
    margin-right: 4px;
  }

  img {
    margin-right: 4px;
  }
}

.fileName {
  margin-left: 3px;
  white-space: nowrap;
}
:deep(.ant-tree-checkbox) {
  transform: translate(-16px, 0px);
}
:deep(.imgOpen) {
  transform: translate(26px, 0px);
}
:deep(.imgOpen2) {
  transform: translate(4px, 0px);
}

.right-tree {
  :deep(.ant-tree-switcher) {
    transform: translate(2px, 2px);
  }
}
:deep(.ant-spin-container) {
  height: 320px;
  overflow-y: scroll;
  transform: translateY(-36px);
}
// :deep(.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle) {
//   width: 0;
// }
:deep(.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle) {
  margin-left: -26px;
  text-align: center;
  margin-right: 2px;
}
</style>
